package org.devside.grails.queue;

/**
 * 线程门, 当门关闭时, 调用线程走到这里会停掉.
 * Date: 2008/04/24
 * Time: 10:54:52
 *
 * @author matianyi@legendapl.com.cn
 */
public class ThreadGate {
    private boolean isOpen; // 门是否关闭

    private int generation; // 第几次关闭

    /**
     * 关门
     */
    public synchronized void close() {
        isOpen = false;
    }

    /**
     * 开门
     */
    public synchronized void open() {
        ++generation;
        isOpen = true;
        notifyAll();
    }

    /**
     * 尝试通过门, 如果门关闭了, 等在门口, 知道门打开
     *
     * @throws InterruptedException 中断异常
     */
    public synchronized void tryPass() throws InterruptedException {
        int currentGeneration = generation;
        while (!isOpen && currentGeneration == generation) {
            wait();
        }
    }
}
